package com.ruoyi.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.text.Convert;
import com.ruoyi.common.exception.BusinessException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.mapper.WebMallUserOrderMapper;
import com.ruoyi.system.service.*;
import com.ruoyi.system.vo.WebMallUserOrderProductSaveVO;
import com.ruoyi.system.vo.WebMallUserOrderSaveVO;
import com.ruoyi.wechat.TemplateMsgUtil;
import com.ruoyi.wechat.config.JsApiPreOrder;
import com.ruoyi.wechat.config.WechatConfig;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;

/**
 * 商城订单Service业务层处理
 *
 * @author wsliupan@126.com
 * @date 2021-06-17
 */
@Service
public class WebMallUserOrderServiceImpl extends ServiceImpl<WebMallUserOrderMapper, WebMallUserOrder> implements IWebMallUserOrderService {
    @Autowired
    private WebMallUserOrderMapper webMallUserOrderMapper;
    @Autowired
    private IWebUserService iWebUserService;

    /**
     * 查询商城订单
     *
     * @param id 商城订单ID
     * @return 商城订单
     */
    @Override
    public WebMallUserOrder selectWebMallUserOrderById(Long id) {
        return webMallUserOrderMapper.selectWebMallUserOrderById(id);
    }

    /**
     * 查询商城订单列表
     *
     * @param webMallUserOrder 商城订单
     * @return 商城订单
     */
    @Override
    public List<WebMallUserOrder> selectWebMallUserOrderList(WebMallUserOrder webMallUserOrder) {
        return webMallUserOrderMapper.selectWebMallUserOrderList(webMallUserOrder);
    }

    /**
     * 新增商城订单
     *
     * @param webMallUserOrder 商城订单
     * @return 结果
     */
    @Override
    public int insertWebMallUserOrder(WebMallUserOrder webMallUserOrder) {
        webMallUserOrder.setCreateTime(DateUtils.getNowDate());
        return webMallUserOrderMapper.insertWebMallUserOrder(webMallUserOrder);
    }

    /**
     * 修改商城订单
     *
     * @param webMallUserOrder 商城订单
     * @return 结果
     */
    @Override
    public boolean updateWebMallUserOrder(WebMallUserOrder webMallUserOrder) {
        //webMallUserOrder.setUpdateTime(DateUtils.getNowDate());
        //return webMallUserOrderMapper.updateWebMallUserOrder(webMallUserOrder);
        return this.saveOrUpdate(webMallUserOrder);
    }

    /**
     * 删除商城订单对象
     *
     * @param ids 需要删除的数据ID
     * @return 结果
     */
    @Override
    public boolean deleteWebMallUserOrderByIds(String ids) {
        //return webMallUserOrderMapper.deleteWebMallUserOrderByIds(Convert.toStrArray(ids));
        return this.removeByIds(Arrays.asList(Convert.toStrArray(ids)));
    }

    /**
     * 删除商城订单信息
     *
     * @param id 商城订单ID
     * @return 结果
     */
    @Override
    public boolean deleteWebMallUserOrderById(Long id) {
        //return webMallUserOrderMapper.deleteWebMallUserOrderById(id);
        return this.removeById(id);
    }

    /**
     * 下单保存
     */
    @Transactional
    public Map<String, Object> saveOrder(WebMallUserOrderSaveVO orderSaveVO) {
        WebUser userData = iWebUserService.getById(orderSaveVO.getUserId());
        if (userData == null) {
            throw new BusinessException(Constants.REQUIRED_FAILD);
        }
        WebUserAddress address = iWebUserAddressService.getOne(new QueryWrapper<WebUserAddress>()
                .eq("id", orderSaveVO.getAddressId())
                .eq("user_id", orderSaveVO.getUserId()));
        if (address == null) {
            throw new BusinessException("地址ID异常");
        }
        if (StringUtils.isEmpty(address.getLatitude())) {
            throw new BusinessException("您当前选择的地址不能精确定位，请使用定位功能重新维护您的地址");
        }
        if (StringUtils.isEmpty(address.getLongitude())) {
            throw new BusinessException("您当前选择的地址不能精确定位，请使用定位功能重新维护您的地址");
        }
        List<Map<String, Object>> productMaps = new ArrayList<>();
        BigDecimal orderMoney = getOrderMoney(orderSaveVO, productMaps);
        BigDecimal payMoney = orderMoney;

        if (productMaps.size() == 0) {
            throw new BusinessException("产品列表信息异常");
        }

        BigDecimal use_score_sum = new BigDecimal("0"); //使用了多少积分
        if (orderSaveVO.getUseScore() != null && 1 == orderSaveVO.getUseScore()) {
            payMoney = useScorePayMoney(userData.getScore(), orderMoney);
            use_score_sum = orderMoney.subtract(payMoney);

            //进行积分处理
            BigDecimal score = new BigDecimal(userData.getScore() + "").subtract(use_score_sum);
            if (score.doubleValue() < 0) {
                throw new BusinessException("用户积分异常");
            }
            Integer freezeScoreVal = 0;
            if (userData.getFreezeScore() != null) {
                freezeScoreVal = userData.getFreezeScore();
            }
            int freezeScore = score.add(new BigDecimal(freezeScoreVal + "")).intValue();
            this.iWebUserService.update(new UpdateWrapper<WebUser>()
                    .eq("id", userData.getId())
                    .set("score", score.intValue())
                    .set("freeze_score", freezeScore));
        }
        WebMallUserOrder mallUserOrder = new WebMallUserOrder();
        mallUserOrder.setUserId(userData.getId());
        mallUserOrder.setOrderNo(StringUtils.seqOrderNum("MALL", 10));
        mallUserOrder.setOrderSum(Long.valueOf(productMaps.size()));
        mallUserOrder.setOrderAmount(orderMoney);
        mallUserOrder.setWaitPayMoney(payMoney);
        mallUserOrder.setOrderType(1l);
        mallUserOrder.setImg((String) productMaps.get(0).get("image"));
        //mallUserOrder.setPayMoney(payMoney);
        mallUserOrder.setPayNo(StringUtils.seqOrderNum("MPAY", 10));
        if (payMoney.doubleValue() == 0) {
            mallUserOrder.setOrderStatus(2l);//待发货
            mallUserOrder.setPayStatus(1l);//已支付
        } else {
            mallUserOrder.setOrderStatus(1l);//待付款
            mallUserOrder.setPayStatus(0l);//未支付
        }

        mallUserOrder.setOrderLinkMobile(address.getMobile());
        mallUserOrder.setOrderlLinkAddress(address.getBaseaddress() + address.getAddress());
        mallUserOrder.setOrderLinkName(address.getUserName());
        mallUserOrder.setUseScoreSum(use_score_sum);
        this.save(mallUserOrder);

        for (Map<String, Object> map : productMaps) {
            WebMallUserOrderProduct orderProduct = new WebMallUserOrderProduct();
            orderProduct.setOrderId(mallUserOrder.getId());
            orderProduct.setProductId(Long.valueOf(map.get("productId") + ""));
            orderProduct.setNumber(Long.valueOf(map.get("number") + ""));
            orderProduct.setProductName(map.get("productName").toString());
            orderProduct.setPrice(new BigDecimal(map.get("targetMoney").toString()));
            orderProduct.setImg(map.get("image").toString());
            if (map.get("skuTitle") != null && map.get("skuValue") != null) {
                orderProduct.setSku((String) map.get("skuTitle") + ":" + map.get("skuValue"));
            }

            iWebMallUserOrderProductService.save(orderProduct);
        }
        Map<String, Object> map = new HashMap<>();
        map.put("orderId", mallUserOrder.getId());
        map.put("payMoney", payMoney);
        Map<String, String> weMap = null;

        if (payMoney.doubleValue() > 0) {
            weMap = jsApiPreOrder.wxPrePay(
                    userData.getWxOpenId(),
                    payMoney.multiply(new BigDecimal("100")).intValue(),
                    mallUserOrder.getOrderNo(),
                    mallUserOrder.getPayNo(),
                    "rest/wechat/washcarPaySuccessNotiry");
            map.put("weMap", weMap);
        }
        return map;
    }

    /**
     * 根据传入的产品ID及选中的SKU，返回产品相关信息并计算出订单金额
     *
     * @param orderSaveVO
     * @param productMaps
     * @return
     */
    public BigDecimal getOrderMoney(WebMallUserOrderSaveVO orderSaveVO, List<Map<String, Object>> productMaps) {
        synchronized (this) {
            if (productMaps == null) productMaps = new ArrayList<>();
            BigDecimal payMoney = new BigDecimal("0");
            if (CollectionUtils.isEmpty(orderSaveVO.getOrderProductSaveVOS())) {
                throw new BusinessException("未传入商品");
            }
            for (WebMallUserOrderProductSaveVO productSaveVO : orderSaveVO.getOrderProductSaveVOS()) {
                if (productSaveVO.getNumber() == null) {
                    throw new BusinessException("商品数量不能为空");
                }
                WebMallProduct product = iWebMallProductService.getById(productSaveVO.getProductId());
                if (product == null) {
                    throw new BusinessException(Constants.REQUIRED_FAILD);
                }
                Map<String, Object> mapData = new HashMap<>();
                String image = null;
                if (StringUtils.isNotEmpty(product.getImages())) {
                    image = product.getImages().split(",")[0];
                }
                mapData.put("image", image);
                mapData.put("productName", product.getProductName());
                mapData.put("productId", product.getId());
                mapData.put("number", productSaveVO.getNumber());
                double targetMoney = product.getTargetMoney();
                if (StringUtils.isNotEmpty(product.getSkuStr())) {
                    if (StringUtils.isEmpty(productSaveVO.getSku())) {
                        throw new BusinessException("请传入选择的sku");
                    }
                    String[] skus = product.getSkuStr().split("-");
                    if (skus.length > 0) {
                        mapData.put("skuTitle", skus[0]);
                        String skuName = skus[0];
                        List<String> values = Arrays.asList(skus[1].split(","));
                        List<Map<String, Object>> listMap = new ArrayList<>();
                        for (String str : values) {
                            Map<String, Object> map = new HashMap<>();
                            String[] val = str.split(":");
                            if (productSaveVO.getSku().equals(val[0])) {
                                targetMoney = Double.valueOf(val[1]);
                                mapData.put("skuValue", val[0]);
                                break;
                            }
                        }
                    }
                    mapData.put("targetMoney", targetMoney);
                    payMoney = new BigDecimal(targetMoney + "").multiply(new BigDecimal(productSaveVO.getNumber() + ""))
                            .add(payMoney);
                    productMaps.add(mapData);
                }
            }
            return payMoney;
        }
    }

    /**
     * 根据积分和订单总金额计算出使用积分后的需要支付的金额
     *
     * @param useScoe
     * @return
     */
    public BigDecimal useScorePayMoney(int useScoe, BigDecimal orderMoney) {
        synchronized (this) {
            BigDecimal payMoney = new BigDecimal("0");
            //计算用户有多少积分转换的钱
            String score_value = iSysConfigService.selectConfigByKey("score_value");
            double scoreMoney = new BigDecimal(useScoe + "").multiply(new BigDecimal(score_value)).doubleValue();
            payMoney = orderMoney.subtract(new BigDecimal(scoreMoney));
            if (payMoney.doubleValue() < 0) {
                payMoney = new BigDecimal(0);
            }
            return payMoney;
        }
    }

    /**
     * 取消订单
     *
     * @param orderId
     * @return
     */
    @Override
    public void cancelOrder(Integer orderId) {
        WebMallUserOrder order = this.getById(orderId);
        if (order == null) {
            throw new BusinessException("订单不存在");
        }
        if (order.getOrderStatus() != 1) {
            throw new BusinessException("当前状态不支持取消");
        }
        WebUser userData = iWebUserService.getById(order.getUserId());
        if (userData != null) {
            //退还积分
            iWebUserService.update(new UpdateWrapper<WebUser>().eq("id", order.getUserId())
                    .set("score", new BigDecimal(userData.getScore()).subtract(order.getUseScoreSum()))
                    .set("freeze_score", new BigDecimal(userData.getFreezeScore()).subtract(order.getUseScoreSum())));
        }
        this.update(new UpdateWrapper<WebMallUserOrder>()
                .eq("id", orderId)
                .set("order_status", 4)); //交易关闭
    }

    /**
     * 支付成功的处理
     *
     * @param pay_no
     * @param payMoney
     * @param transaction_id
     * @param result_code
     */
    @Transactional
    public void paySuccess(String pay_no, double payMoney, String transaction_id, String result_code) {
        synchronized (this) {
            // 更新支付状态等信息
            WebMallUserOrder userOrder = this.getOne(new QueryWrapper<WebMallUserOrder>()
                    .eq("pay_no", pay_no).eq("pay_status", 0));
            if (userOrder != null) {
                this.update(new UpdateWrapper<WebMallUserOrder>()
                        .eq("id", userOrder.getId())
                        .set("order_status", 2)//代发货
                        .set("pay_status", 1)//已支付
                        .set("pay_time", DateUtils.getNowDate())
                        .set("pay_money", payMoney)
                );
            }

            if (userOrder.getUseScoreSum().doubleValue() > 0) {
                //处理用户积分
                WebUser user = iWebUserService.getById(userOrder.getUserId());
                if (user != null) {
                    iWebUserService.update(new UpdateWrapper<WebUser>()
                            .eq("id", user.getId())
                            .set("freeze_score", new BigDecimal(user.getFreezeScore()).subtract(userOrder.getUseScoreSum()))
                    );
                }
                //推送消息
                try {
                    Map<String, String> map = new HashMap<String, String>();
                    map.put("keyword1",userOrder.getOrderNo());//单号
                    map.put("keyword2",payMoney+"");//金额
                    map.put("keyword3",DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS, DateUtils.getNowDate()));//支付时间
                    map.put("keyword4","订单支付成功，点击查看订单详情");//温馨提示
                    map.put("form_id", ""/*rechargeLog.getPrepayId()*/);
                    map.put("page", "/pages/member/paylog");
                    TemplateMsgUtil.orderPayPush(user.getWxOpenId(), map);
                }catch (Exception e){
                    log.error("推送消息失败"+e.getMessage());
                }
            }

            //支付记录
            WebMallUserOrderPay orderPay = new WebMallUserOrderPay();
            orderPay.setUserId(userOrder.getUserId());
            orderPay.setOrderId(userOrder.getId());
            orderPay.setOrderNo(userOrder.getOrderNo());
            orderPay.setTotalFee(payMoney);
            orderPay.setTradeType("2");
            orderPay.setGoodsTag(transaction_id);
            iWebMallUserOrderPayService.save(orderPay);

            //积分扣减记录
            WebUserScoreAward scoreAward = new WebUserScoreAward();
            scoreAward.setUserId(userOrder.getUserId());
            scoreAward.setAmout(-userOrder.getUseScoreSum().longValue());
            scoreAward.setType(1L); //一级奖励s
            iWebUserScoreAwardService.save(scoreAward);

            //新订单推送给门店师傅
//            List<Integer> shifuIds = sysEmployeePostMapper.selectDeptUserByPost(orderWashcar.getDeptId(), 1);
//            if (CollectionUtils.isNotEmpty(shifuIds)) {
//                for (Integer id : shifuIds) {
//                    User user = userMapper.selectById(id);
//                    Map<String, Object> mapCar = _carMapper.select3(orderWashcar.getCarId());
//                    SysDept dept = deptMapper.selectDeptById(Long.valueOf(orderWashcar.getDeptId() + ""));
//                    //推送消息
//                    Map<String, String> map = new HashMap<String, String>();
//                    map.put("first", dept.getDeptName() + "有新洗车订单！(预约单)");
//                    map.put("keyword1", orderWashcar.getOrderNo());//订单号
//                    map.put("keyword2", DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS, orderWashcar.getCreateTime()));//订单时间
//                    map.put("remark", "车辆位置：" + mapCar.get("address") + mapCar.get("carport") + " " + mapCar.get("car_no"));
//                    map.put("pagepath", "/pages/EmPlat/orderlist");
//                    map.put("url", wechatConfig.getDomain());
//                    TemplateMsgUtil.newOrderPush(user.getWxOpenId(), map);
//                }
//            }
        }
    }


    @Autowired
    private ISysConfigService iSysConfigService;
    @Autowired
    private IWebMallProductService iWebMallProductService;
    @Autowired
    private IWebUserAddressService iWebUserAddressService;
    @Autowired
    private IWebMallUserOrderProductService iWebMallUserOrderProductService;
    @Autowired
    private JsApiPreOrder jsApiPreOrder;
    @Autowired
    private IWebMallUserOrderPayService iWebMallUserOrderPayService;
    @Autowired
    private IWebUserScoreAwardService iWebUserScoreAwardService;
    @Autowired
    private WechatConfig wechatConfig;

}
